package com.hk.core.autoconfigure.exception.servlet;

import com.hk.commons.JsonResult;
import com.hk.commons.Status;
import com.hk.commons.util.SpringContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;



/**
 * 对于 webmvc异常的处理
 *
 * @author Kevin
 */
@RestControllerAdvice
public class WebmvcExceptionHandler extends AbstractExceptionHandler {

    /**
     * <p>
     * 对于不是指定的方法请求时，将抛出 HttpRequestMethodNotSupportedException.<br/>
     * 响应状态码： 405
     * </p>
     *
     * @param e       e
     * @param request request
     * @return {@link JsonResult}
     */
    @ExceptionHandler(value = {HttpRequestMethodNotSupportedException.class})
    @ResponseStatus(HttpStatus.OK)
    public JsonResult<Void> httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        error(e, e.getMessage(), request);
        return new JsonResult<>(Status.METHOD_NOT_ALLOWED, SpringContextHolder.getMessage("access.resources.no.support.message", e.getMethod()));
    }

    /**
     * <p>
     * 客户端请求参数格式不正确或请求出错时，将抛出 ServletRequestBindingException.<br/>
     * 响应状态码： 400
     * </p>
     *
     * @param e       e
     * @param request request
     * @return {@link JsonResult}
     */
    @ExceptionHandler(value = {ServletRequestBindingException.class})
    @ResponseStatus(HttpStatus.OK)
    public JsonResult<Void> servletRequestBindingException(ServletRequestBindingException e, HttpServletRequest request) {
        error(e, e.getMessage(), request);
        return JsonResult.badRequest(SpringContextHolder.getMessage("request.error.message"));
    }


    /**
     * 404
     * 需要在 application.yml中配置 spring.mvc.throw-exception-if-no-handler-found: true
     * 默认为false（404时不抛出异常）
     *
     * @param e       e
     * @param request request
     * @return {@link JsonResult}
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.OK)
    public JsonResult<Void> noHandlerFoundException(NoHandlerFoundException e, HttpServletRequest request) {
        error(e, e.getMessage(), request);
        return new JsonResult<>(Status.NOT_FOUND,
                String.format("%s %s %s", Status.NOT_FOUND.getMessage(), e.getHttpMethod(), e.getRequestURL()));
    }
}
